package com.innovation.ic.im.end.base.service.im_erp9.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.innovation.ic.im.end.base.mapper.im_erp9.ChatPairMapper;
import com.innovation.ic.im.end.base.mapper.im_erp9.TempChatPairMapper;
import com.innovation.ic.im.end.base.model.im_erp9.ChatPair;
import com.innovation.ic.im.end.base.model.im_erp9.TempChatPair;
import com.innovation.ic.im.end.base.pojo.ServiceResult;
import com.innovation.ic.im.end.base.pojo.constant.Constants;
import com.innovation.ic.im.end.base.pojo.constant.ToppingType;
import com.innovation.ic.im.end.base.pojo.enums.ChatPageStatusEnum;
import com.innovation.ic.im.end.base.service.im_erp9.ChatPairService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * ChatPair的具体实现类
 */
@Service
@Transactional
public class ChatPairServiceImpl extends ServiceImpl<ChatPairMapper, ChatPair> implements ChatPairService {
    private static final Logger log = LoggerFactory.getLogger(ChatPairServiceImpl.class);

    @Autowired
    private ChatPairMapper chatPairMapper;

    @Autowired
    private TempChatPairMapper tempChatPairMapper;

    /**
     * 删除chat_pair表中的所有数据
     *
     * @return
     */
    @Override
    public ServiceResult<Boolean> truncateTable() {
        ServiceResult<Boolean> serviceResult = new ServiceResult<Boolean>();
        chatPairMapper.truncateTable();

        serviceResult.setMessage(ServiceResult.DELETE_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 添加ChatPair对象
     *
     * @param chatPair
     * @return
     */
    @Override
    public ServiceResult<Boolean> saveChatPair(ChatPair chatPair) {
        Boolean result = Boolean.FALSE;

        ServiceResult<Boolean> serviceResult = new ServiceResult<Boolean>();
        int insert = baseMapper.insert(chatPair);
        if(insert > 0){
            result = Boolean.TRUE;
        }

        serviceResult.setMessage(ServiceResult.INSERT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 批量插入ChatPair对象
     *
     * @param chatPairList
     * @return
     */
    @Override
    public ServiceResult<Boolean> saveChatPairList(List<ChatPair> chatPairList) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<Boolean>();
        baseMapper.insertBatchSomeColumn(chatPairList);

        serviceResult.setMessage(ServiceResult.INSERT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 根据fromUserAccount，查找ChatPair对象
     *
     * @param fromUserAccount
     * @return
     */
    @Override
    public ServiceResult<ChatPair> findByFromUserAccountAndToUserAccount(String fromUserAccount) {
        ServiceResult<ChatPair> serviceResult = new ServiceResult<ChatPair>();
        ChatPair chatPair = new ChatPair();
        chatPair.setFromUserAccount(fromUserAccount);
        QueryWrapper<ChatPair> queryWrapper = new QueryWrapper<>(chatPair);
        chatPair = baseMapper.selectOne(queryWrapper);

        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(chatPair);
        return serviceResult;
    }

    /**
     * 更新last_contact_time字段，两条记录都要更新
     * @param fromUserAccount
     * @param toUserAccount
     * @return 返回更新结果
     */
    @Override
    public ServiceResult<Boolean> updateAccountLastContactTime(String fromUserAccount, String toUserAccount) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();

        Boolean result = Boolean.FALSE;

        // 先查询两人的最近联系时间，为空时，记录最近联系时间
        Date date = chatPairMapper.getLastContactTime(fromUserAccount, toUserAccount);
        if(date == null){
            // 更新聊天对的最近联系时间
            int update = chatPairMapper.updateLastContactTime(fromUserAccount, toUserAccount);
            if(update > 0){
                log.info("更新用户:[{}]与[{}]在chat_pair表的最近联系时间完成", fromUserAccount, toUserAccount);
                result = Boolean.TRUE;
            }
        }

        serviceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 更新last_contact_time字段，两条记录都要更新
     * @param fromUserAccount
     * @param toUserAccount
     * @return 返回更新结果
     */
    @Override
    public ServiceResult<Boolean> updateLastContactTime(String fromUserAccount, String toUserAccount) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<Boolean>();

        // 更新聊天对的最近联系时间
        int update = chatPairMapper.updateLastContactTime(fromUserAccount, toUserAccount);
        if(update > 0){
            log.info("更新用户:[{}]与[{}]在chat_pair表的最近联系时间完成", fromUserAccount, toUserAccount);
        }

        // 不是自己给自己发送消息的情况才需要更新对方与自己的聊天对最近联系时间
        if(!fromUserAccount.equals(toUserAccount)){
            int update1 = chatPairMapper.updateLastContactTime(toUserAccount, fromUserAccount);
            if(update1 > 0){
                log.info("更新用户:[{}]与[{}]在chat_pair表的最近联系时间完成", toUserAccount, fromUserAccount);
            }
        }

        serviceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 根据发送账号，接收账号,状态,去设置置顶时间
     *
     * @param fromUserAccount
     * @param toUserAccount
     * @param status
     * @return
     */
    @Override
    public ServiceResult<Boolean> updateCharPair(String fromUserAccount, String toUserAccount, Integer status) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<Boolean>();

        UpdateWrapper<ChatPair> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("from_user_account", fromUserAccount);
        updateWrapper.eq("to_user_account", toUserAccount);
        if (status.equals(ToppingType.YES)) {
            ChatPair chatPair = new ChatPair();
            chatPair.setToppingTime(new Date(System.currentTimeMillis()));
            int update = baseMapper.update(chatPair, updateWrapper);
            if(update > 0){
                log.info("用户:[{}]将用户:[{}]置顶成功", fromUserAccount, toUserAccount);
            }
        } else {
            ChatPair chatPair = new ChatPair();
            chatPair.setToppingTime(null);
            int update = baseMapper.update(chatPair, updateWrapper);
            if(update > 0){
                log.info("用户:[{}]将用户:[{}]取消置顶成功", fromUserAccount, toUserAccount);
            }
        }
        serviceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 根据用户设置一对一聊天内容不可见时间
     * @param map 查询条件
     * @return 返回结果
     */
    @Override
    public ServiceResult<Boolean> invisibleChatRecordSet(Map<String, Object> map) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();

        log.info("根据参数:[{}]设置聊天记录不可见时间", new JSONObject(map).toJSONString());
        Boolean result = setContentInvisibleTimeByAccount(String.valueOf(map.get(Constants.FROM_USER_ACCOUNT)), String.valueOf(map.get(Constants.TO_USER_ACCOUNT)));

        serviceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 删除最近联系人并清除聊天记录
     * @param map 查询条件
     * @return 返回处理结果
     */
    @Override
    public ServiceResult<Boolean> deleteChat(Map<String, Object> map) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        Boolean result = false;

        // 删除最近联系人，清空chatPair中的最近联系时间
        String fromUserAccount = String.valueOf(map.get(Constants.FROM_USER_ACCOUNT));
        String toUserAccount = String.valueOf(map.get(Constants.TO_USER_ACCOUNT));
        int count = chatPairMapper.deleteChat(fromUserAccount, toUserAccount);
        if(count > 0){
            log.info("清空chatPair中fromUserAccount=[{}],toUserAccount=[{}]的最近联系时间成功", fromUserAccount, toUserAccount);
            // 清除聊天记录
            result = setContentInvisibleTimeByAccount(fromUserAccount, toUserAccount);
        }

        serviceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 更新某个用户与某个用户的聊天页面打开状态
     * @param fromUserAccount 发送消息的用户
     * @param toUserAccount 接收消息的用户
     * @param status 状态。0表示聊天窗口关闭，1表示聊天窗口打开
     * @return 返回结果
     */
    @Override
    public ServiceResult<Boolean> updateChatPageStatus(String fromUserAccount, String toUserAccount, Integer status) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();

        if(status == ChatPageStatusEnum.OPEN.getCode().intValue()){
            // 修改所有人的聊天页面状态为关闭
            chatPairMapper.closeAccountChatPageStatus(fromUserAccount);
        }
        chatPairMapper.updateChatPageStatus(fromUserAccount, toUserAccount, status);

        serviceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(Boolean.TRUE);
        return serviceResult;
}

    /**
     * 将当前用户所有的聊天页面状态设置为关闭
     * @param username 用户名
     * @return 返回结果
     */
    @Override
    public ServiceResult<Boolean> closeAccountChatPageStatus(String username) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();

        chatPairMapper.closeAccountChatPageStatus(username);

        serviceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 获取用户A与用户B的聊天页面打开状态
     * @param fromUserAccount 发送消息的用户
     * @param toUserAccount   接收消息的用户
     * @return 返回聊天页面打开状态(0 : 表示聊天窗口关闭 、 1 : 表示聊天窗口打开)
     */
    @Override
    public ServiceResult<Integer> getChatPageStatus(String fromUserAccount, String toUserAccount) {
        ServiceResult<Integer> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(chatPairMapper.getChatPageStatus(fromUserAccount, toUserAccount));
        return serviceResult;
    }

    /**
     * 删除历史供应商协同账号的聊天对数据
     * @param scAccountId 供应商协同账号
     * @return 返回删除结果
     */
    @Override
    public ServiceResult<Boolean> deleteScChatPairData(String scAccountId) {
        Boolean result = Boolean.FALSE;

        int delete = chatPairMapper.deleteScChatPairData(scAccountId);
        if(delete > 0){
            result = Boolean.TRUE;
            log.info("删除历史供应商协同账号与采购的聊天对数据成功");
        }

        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(result);
        serviceResult.setMessage(ServiceResult.DELETE_SUCCESS);
        return serviceResult;
    }

    /**
     * 获取最大的code
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<Integer> getMaxCode() {
        Integer result = chatPairMapper.getChatPairMaxCode();
        ServiceResult<Integer> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 根据账号查询聊天对数据
     * @param fromUserAccount 发送消息的用户账号
     * @param toUserAccount 接收消息的用户账号
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<List<ChatPair>> selectDataByAccount(String fromUserAccount, String toUserAccount) {
        QueryWrapper<ChatPair> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Constants.FROM_USER_ACCOUNT_FIELD, fromUserAccount);
        queryWrapper.eq(Constants.TO_USER_ACCOUNT_FIELD, toUserAccount);
        List<ChatPair> result = chatPairMapper.selectList(queryWrapper);

        ServiceResult<List<ChatPair>> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 备份chat_pair表中设置了置顶时间、最近联系时间、内容不可见时间和设置了免打扰的数据到temp_chat_pair表中
     * @return 返回备份结果
     */
    @Override
    public ServiceResult<Boolean> backupLastContactInvisibleIsNotNullData() {
        ServiceResult<Boolean> serviceResult = new ServiceResult<Boolean>();

        Boolean result = false;
        // 查询设置了置顶时间、最近联系时间、内容不可见时间和设置了免打扰的数据
        List<TempChatPair> list = chatPairMapper.getNoReminderLastContactInvisibleIsNotNullData();
        if(list == null || list.size() == 0){
            log.info("设置了置顶时间、最近联系时间、内容不可见时间和设置了免打扰的数据为空,无需备份");
            serviceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
            serviceResult.setSuccess(Boolean.TRUE);
            serviceResult.setResult(Boolean.TRUE);
            return serviceResult;
        }

        // 备份设置了置顶时间、最近联系时间、内容不可见时间和设置了免打扰的数据
        log.info("备份设置了置顶时间、最近联系时间、内容不可见时间和设置了免打扰的数据,需备份的数据条数:[{}]", list.size());
        Integer count = tempChatPairMapper.insertBatchSomeColumn(list);

        if(count > 0){
            result = true;
            log.info("备份设置了置顶时间、最近联系时间、内容不可见时间和设置了免打扰的数据,需备份的数据完成,数据备份条数:[{}]", list.size());
        }

        serviceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 将char_pair备份的数据更新到原表中
     * @return 返回更新结果
     */
    @Override
    public ServiceResult<Boolean> insertTempDataToChatpair() {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();

        // 查询char_pair表已经备份的数据
        List<TempChatPair> list = tempChatPairMapper.selectList(new QueryWrapper<>());
        if(list == null || list.size() == 0){
            log.info("char_pair备份的数据为空,无需处理");
            serviceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
            serviceResult.setSuccess(Boolean.TRUE);
            serviceResult.setResult(Boolean.TRUE);
            return serviceResult;
        }

        log.info("需要处理的备份数据条数:[{}]", list.size());
        int count = 0;
        for (int i = 0; i < list.size(); i++) {
            TempChatPair tempChatPair = list.get(i);
            ChatPair chatPair = new ChatPair();
            // 置顶时间
            if(tempChatPair.getToppingTime() != null){
                chatPair.setToppingTime(tempChatPair.getToppingTime());
            }

            // 最近联系时间
            if(tempChatPair.getLastContactTime() != null){
                chatPair.setLastContactTime(tempChatPair.getLastContactTime());
            }

            // 内容不可见时间
            if(tempChatPair.getContentInvisibleTime() != null){
                chatPair.setContentInvisibleTime(tempChatPair.getContentInvisibleTime());
            }

            // 是否免打扰
            if(tempChatPair.getNoReminder() != null){
                chatPair.setNoReminder(tempChatPair.getNoReminder());
            }

            UpdateWrapper<ChatPair> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq(Constants.FROM_USER_ACCOUNT_FIELD, tempChatPair.getFromUserAccount());
            updateWrapper.eq(Constants.TO_USER_ACCOUNT_FIELD, tempChatPair.getToUserAccount());
            int update = chatPairMapper.update(chatPair, updateWrapper);
            if(update > 0){
                count++;
            }
        }
        log.info("处理成功的备份数据条数:[{}]", count);

        serviceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 查询当前账号的最近联系人账号集合
     * @param account 账号
     * @return 返回当前账号的最近联系人账号集合
     */
    @Override
    public ServiceResult<List<String>> selectLastContactAccounts(String account) {
        ServiceResult<List<String>> serviceResult = new ServiceResult<>();
        List<String> list = new ArrayList<>();

        // 查找当前联系人所有最近联系人账号集合
        if(!Strings.isNullOrEmpty(account)){
            list = chatPairMapper.selectLastContactAccounts(account);
        }

        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(list);
        return serviceResult;
    }

    /**
     * 设置某个用户对某个用户消息免打扰
     * @param fromUserAccount 发送消息的用户
     * @param toUserAccount 接收消息的用户
     * @param status 状态。1表示设置为消息免打扰。0表示取消消息免打扰
     * @return 返回结果
     */
    @Override
    public ServiceResult<Boolean> noReminder(String fromUserAccount, String toUserAccount, Integer status) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        Boolean result = Boolean.FALSE;
        String message = ServiceResult.UPDATE_FAIL;

        // 设置某个用户对某个用户消息免打扰
        int update = chatPairMapper.updateNoReminder(fromUserAccount, toUserAccount, status);
        if(update > 0){
            result = Boolean.TRUE;
            message = ServiceResult.UPDATE_SUCCESS;
            if(status == 1){
                log.info("设置用户:[{}]对用户:[{}]消息免打扰成功", fromUserAccount, toUserAccount);
            }else{
                log.info("取消用户:[{}]对用户:[{}]消息免打扰成功", fromUserAccount, toUserAccount);
            }
        }

        serviceResult.setMessage(message);
        serviceResult.setSuccess(result);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 根据账号更新聊天记录不可见时间
     * @param fromUserAccount 发送消息的用户账号
     * @param toUserAccount 接收消息的用户账号
     * @return 返回更新结果
     */
    private Boolean setContentInvisibleTimeByAccount(String fromUserAccount, String toUserAccount){
        Boolean result = Boolean.FALSE;

        // 更新的字段值
        ChatPair chatPair = new ChatPair();
        chatPair.setContentInvisibleTime(new Date(System.currentTimeMillis()));

        // 更新数据的查询条件
        UpdateWrapper<ChatPair> param = new UpdateWrapper<>();
        param.eq(Constants.FROM_USER_ACCOUNT_FIELD, fromUserAccount);
        param.eq(Constants.TO_USER_ACCOUNT_FIELD, toUserAccount);

        int update = chatPairMapper.update(chatPair, param);
        if(update > 0){
            log.info("根据参数fromUserAccount=[{}],toUserAccount=[{}]设置聊天记录不可见时间成功", fromUserAccount, toUserAccount);
            result = true;
        }else{
            log.warn("根据参数fromUserAccount=[{}],toUserAccount=[{}]设置聊天记录不可见时间失败", fromUserAccount, toUserAccount);
        }
        return result;
    }
}